package app

import (
	"fmt"
	"game-server/app/common/request"
	"game-server/app/common/response"
	"game-server/app/services"
	"game-server/global"
	"game-server/utils"
	"path"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// Register 用户注册
// @Summary 用户注册
// @Description 门户用户 用户注册
// @Tags 门户用户
// @Accept json
// @Produce json
// @Param data body request.Register true "请求参数"
// @Router /gameServer/auth/register [post]
func Register(c *gin.Context) {
	var form request.Register
	if err := c.ShouldBindJSON(&form); err != nil {
		response.ValidateFail(c, request.GetErrorMsg(form, err))
		return
	}

	if err, user := services.UserService.Register(form); err != nil {
		response.BusinessFail(c, err.Error())
	} else {
		response.Success(c, user)
	}
}

// PutHeaderImage 上传文件
// @Summary 上传文件
// @Description 上传文件
// @Tags 上传文件
// @Accept multipart/form-data
// @Produce json
// @Param file formData file true "文件"
// @Router /gameServer/auth/upload [post]
func PutHeaderImage(c *gin.Context) {
	file, _ := c.FormFile("file")
	if file == nil {
		response.BusinessFail(c, "请选择上传文件")
		return
	}

	fileObj, err := file.Open()
	if err != nil {
		global.App.Log.Error("文件打开失败", zap.Any("err", err))
		return
	}

	// 生成唯一文件名
	ext := path.Ext(file.Filename)
	fileName := fmt.Sprintf("%s_%s%s",
		time.Now().Format("20060102150405"),
		utils.RandString(8),
		ext,
	)

	// 把文件上传到minio对应的桶中
	ok := global.UploadFile(global.App.Config.Minio.BucketName, fileName, fileObj, file.Size)
	if !ok {
		response.BusinessFail(c, "上传头像失败")
		return
	}
	// 拼接文件访问地址
	fileUrl := "/" + global.App.Config.Minio.BucketName + "/" + fileName
	fullFileUrl := global.App.Config.Minio.Endpoint + fileUrl
	// response.Success(c, fileUrl)
	response.Success(c, gin.H{
		"baseUrl": global.App.Config.Minio.Endpoint,
		"url":     fileUrl,
		"fullUrl": fullFileUrl,
	})
}
